/**
author: sailing
date: 2016/11/17
fun： 获取数据去画topo
***/
import fetchJson from './fetchJson'
import draw from './draw'
import Config from './config'
import tools from './tools'
import counter from './counter'
import eventBus from '../eventBus'
import setPosition from './setPosition'
import dataJson from './data'
import selectPort from './selectPort'
export default {

    draw(flag) {
        var _url = "/diagram/getdata/?name=" + Config.bizx


        if (Config.dev) {
            this.callback(Config.topoData)
            return
        }

        console.log("config.topoD topoD:", Config.topoD)

        if (Config.topoD === 'yes') {
            this.draw_canvas()
            return
        }


        fetchJson.getJson({
            self: this,
            url: _url,
            callback: this.saveBack,
            error: this.error
        })

    },

    saveBack(res) {
        if (res.code == 1) {
            let data = JSON.parse(res.data)
            this.callback(data, true)
        } else {
            this.draw_canvas()
        }
    },

    draw_canvas(cy) {

        var _url = '/topology/inforeticlearound/?equipment_id=' + Config.bizx
        if (Config.topoD === 'yes') {
            _url = '/topology/distribution/?equipment_id=' + Config.bizx
                // eventBus.bus.$emit('hideAllBnt')
        }

        fetchJson.getJson({
            self: this,
            url: _url,
            callback: this.callback,
            error: this.error
        })

        fetchJson.getJson({
            self: this,
            url: '/topology/board_of_equipment/?id=' + Config.bizx,
            callback: this.callbackBoard,
            error: this.error
        })
    },

    callbackBoard(json) {
        if (json.code === 1) {
            eventBus.bus.$emit('handlerCaowei', json.data)
        } else {
            // alert(json.message)
            Config.topVue.$message('没有异常端口');
        }
    },

    setDataCon(data) {
        var nodes = data.nodes
        for (var i = 0; i < nodes.length; i++) {
            var position = {
                x: 100 + i * 80,
                y: 100 + i * 80
            }
            nodes[i]['position'] = position
        }
    },

    setId(arr) {

        for (var i = 0; i < arr.length; i++) {
            console.log('arr[i].data:', arr[i].data[i])
            arr[i].data['id'] = tools.getUUID()
            arr[i].data['drawState'] = true
        }
    },

    setNodeId(nodes) {
        for (var i = 0; i < nodes.length; i++) {
            nodes[i].data['flag'] = true
            nodes[i].data['oldLabel'] = nodes[i].data['label']
            if (!nodes[i].data['type']) nodes[i].data['type'] = "switch"
        }
    },

    hideDistribution(d) {

        if (!d.dStatus) {
            this.draw()
            return
        }


        var _url = "/diagram/getdata/?name=" + Config.bizx + "_hide"

        fetchJson.getJson({
            self: this,
            url: _url,
            callback: this.hideBack,
            error: this.error
        })


    },

    hideBack(res) {
        if (res.code == 1) {
            let data = JSON.parse(res.data)
            this.callback(data, true)
        } else {
            this.draw_hide()
        }
    },

    draw_hide() {
        var uPath = '/topology/inforeticlearound/?equipment_id=' + Config.bizx + '&skip_dis_cab=1'
        fetchJson.getJson({
            self: this,
            url: uPath,
            callback: this.callback,
            error: this.error
        })
    },

    refresh(d) {
        var uPath = '/topology/inforeticlearound/?equipment_id=' + Config.bizx + '&skip_dis_cab=1'
        if (!d.dStatus) {
            uPath = '/topology/inforeticlearound/?equipment_id=' + Config.bizx
        }
        fetchJson.getJson({
            self: this,
            url: uPath,
            callback: this.callback,
            error: this.error
        })
    },


    saveTopo() {
        var uPath = '/diagram/direct_create/'
        var djson = dataJson.cy.json()
        var elements = djson.elements
        var name = Config.bizx

        if (Config.dStatus) {
            name = Config.bizx + "_hide"
        }

        var sendD = {
            name: name,
            data: JSON.stringify(elements)
        }
        fetchJson.postJson({
            self: this,
            url: uPath,
            data: sendD,
            callback: this.savecallback,
            error: this.error
        })
    },

    savecallback(res) {
        var message = ''
        if (res.code == 1 || res.code == '1') {
            message = '保存成功'
        } else {
            message = '保存成功！'
        }
        //alert("保存成功！")
        Config.topVue.$message(dataC.master)
    },

    findLN(type, obj) {
        var flag = false
        var arrEdges = dataJson.edges
        var arrNodes = dataJson.nodes
        if (type === 'node') {
            for (let i = 0; i < arrNodes.length; i++) {
                console.log('node :', obj.id === arrNodes[i]['data'].id, obj.data.id, arrNodes[i]['data'].id)
                if (obj.data.id === arrNodes[i]['data'].id) {
                    return true
                }
            }
            return false
        }

        if (type === 'line') {
            for (var i = 0; i < arrEdges.length; i++) {
                var objD = obj['data']
                var aE = arrEdges[i]['data']
                    // console.log('obj[data]: ', obj['data'], arrEdges[i]['data'])
                if (objD['source'] == aE['source'] &&
                    objD['target'] == aE['target'] &&
                    objD['e_port'] == aE['e_port'] &&
                    objD['s_port'] == aE['s_port']) {
                    // console.log('ggggggggggggggggggggggggggggggggggggg')
                    return true
                }

                if (objD['source'] == aE['target'] &&
                    objD['target'] == aE['source'] &&
                    objD['e_port'] == aE['s_port'] &&
                    objD['s_port'] == aE['e_port']) {
                    // console.log('kkkkkkkkkkkkkkkkkkkkkkkk')
                    return true
                }
            }
            return false
        }
    },

    addNextNode(data, id) {

        if (Config.bizx != id) {
            for (let i = 0; i < data.nodes.length; i++) {
                if (!this.findLN('node', data.nodes[i])) {
                    dataJson.nodes.push(data.nodes[i])
                }
            }

            for (let i = 0; i < data.edges.length; i++) {
                if (!this.findLN('line', data.edges[i])) {
                    dataJson.edges.push(data.edges[i])
                }
            }
        } else {
            dataJson.nodes = data.nodes
            dataJson.edges = data.edges
        }



        this.callback(dataJson, '', true)
        if (Config.bizx != id) {
            dataJson.cy.nodes(function(i, node) {
                var data = node.data()
                if (data.id == id) {
                    node.addClass('DoderBlue')
                        // node.layoutDimensions(position)
                }
            })
        }

    },

    callback(data, flag, lay) {
        var that = this
        dataJson.cy.width(1000)
        dataJson.cy.height(1000)
        dataJson.cy.reset()
        console.log("canvae width height:", dataJson.cy.width(), dataJson.cy.height(), document.getElementById('containerApp'), tools.getPageHeight(), tools.getPageWidth())
        dataJson.cy.zoom({ level: 1 })
        dataJson.cy.maxZoom(1.5)
        dataJson.cy.minZoom(0.2)
        dataJson.cy.edges(function(i, edge) {
            dataJson.cy.remove(edge)
        })
        dataJson.cy.nodes(function(i, node) {
            dataJson.cy.remove(node)
        })
        this.setId(data.edges)
        this.setNodeId(data.nodes)
        dataJson.nodes = data.nodes
        dataJson.edges = data.edges
            // setPosition.posi(data)
        dataJson.cy.add(data.nodes)
        dataJson.cy.add(data.edges)
        var number = 1.2
        if (dataJson.nodes.length < 50) {
            number = 0.5
        }
        if (dataJson.nodes.length < 20) {
            number = 0
        }

        if (!flag) {
            if (dataJson.nodes.length < 20) {
                dataJson.cy.layout({
                    name: 'breadthfirst',
                    directed: true,
                    padding: 10
                })
            } else {
                dataJson.cy.layout({
                    name: 'breadthfirst',
                    fit: false, // whether to fit the viewport to the graph
                    directed: false, // whether the tree is directed downwards (or edges can point in any direction if false)
                    padding: 0, // padding on fit
                    circle: true, // put depths in concentric circles if true, put depths top down if false
                    grid: true,
                    spacingFactor: number, // positive spacing factor, larger => more space between nodes (N.B. n/a if causes overlap)
                    boundingBox: undefined, // constrain layout bounds; { x1, y1, x2, y2 } or { x1, y1, w, h }
                    avoidOverlap: true, // prevents node overlap, may overflow boundingBox if not enough space
                    roots: undefined, // the roots of the trees
                    maximalAdjustments: 10, // how many times to try to position the nodes in a maximal way (i.e. no backtracking)
                    animate: false, // whether to transition the node positions
                    animationDuration: 500, // duration of animation in ms if enabled
                    animationEasing: undefined, // easing of animation if enabled
                    ready: undefined, // callback on layoutready
                    stop: undefined // callback on layoutstop
                })
            }
        }
        draw.setNodeStyle(dataJson.cy)
        var coun = counter.getCounter(data.nodes)

        dataJson.cy.nodes(function(i, node) {
            var data = node.data()

            if (data.master) {
                dataJson.master = data
                node.addClass('eater')
            }
        })

        eventBus.bus.$emit('sendCounter', coun)
    },
    error() {}
}